<template>
  <view class="container" @refresherrefresh="onRefresh" refresher-enabled :refresher-triggered="refreshing">
    <view class="filter-bar">
      <scroll-view scroll-x class="filter-scroll">
        <view class="filter-buttons">
          <view 
            v-for="(item, index) in filterTypes"
            :key="index"
            class="filter-btn" 
            :class="{ active: currentType === item.type }" 
            @click="handleFilterChange(item.type)"
          >
            {{ item.label }} ({{ item.count }})
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="summary-card">
      <view class="summary-header">
        <text class="summary-title">评价总览</text>
      </view>
      <view class="summary-content">
        <view class="summary-rating">
          <text class="rating-score">{{ stats.averageRating.toFixed(1) }}</text>
          <text class="rating-max">/5</text>
        </view>
        <view class="summary-stats">
          <view class="stat-item">
            <u-rate 
              :value="stats.averageRating" 
              readonly 
              size="16" 
              active-color="#00b578" 
              inactive-color="#b2b2b2"
            ></u-rate>
            <text class="stat-text">综合评分</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ stats.goodRatePercentage.toFixed(1) }}%</text>
            <text class="stat-text">好评率</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ stats.totalCount }}</text>
            <text class="stat-text">评价总数</text>
          </view>
        </view>
      </view>
    </view>

    <view class="reviews-list">
      <view v-if="loading.list" class="loading-box">
        <uni-load-more status="loading" iconType="snow"></uni-load-more>
      </view>
      
      <template v-else>
        <view class="review-card" v-for="item in reviewList" :key="item.id">
          <view class="review-header">
            <view class="user-info">
              <u-avatar :src="item.avatar" shape="circle" size="40"></u-avatar>
              <view class="user-details">
                <text class="user-name">{{ item.userName }}</text>
                <view class="user-meta">
                  <text class="user-time">{{ item.createTime }}</text>
                  <text class="user-location">IP属地：{{ item.ipLocation }}</text>
                </view>
              </view>
            </view>
            <view class="rating-box">
              <u-rate
                :value="item.rating"
                readonly
                size="16"
                active-color="#00b578"
                inactive-color="#b2b2b2"
              ></u-rate>
            </view>
          </view>
          
          <view class="review-content">
            <text class="review-text">{{ item.content }}</text>
          </view>
          
          <view class="review-images" v-if="item.images && item.images.length">
            <image 
              v-for="(img, imgIndex) in item.images" 
              :key="imgIndex"
              :src="img" 
              mode="aspectFill" 
              class="review-image"
              @click="previewImage(item.images, imgIndex)"
            ></image>
          </view>
          
          <view class="review-footer">
            <view class="action-btn" @click="handleLike(item)">
              <u-icon 
                :name="item.isLiked ? 'thumb-up-fill' : 'thumb-up'" 
                size="20" 
                :color="item.isLiked ? '#00b578' : '#999'"
              ></u-icon>
              <text :class="{ 'liked': item.isLiked }">{{ item.likeCount || 0 }}</text>
            </view>
            <view class="action-btn" @click="showReplyInput(item)">
              <u-icon name="chat" size="20" color="#999"></u-icon>
              <text>回复 {{ item.replyCount || 0 }}</text>
            </view>
            <view class="action-btn" v-if="item.isOwner" @click="handleDelete(item)">
              <u-icon name="trash" size="20" color="#999"></u-icon>
              <text>删除</text>
            </view>
          </view>

          <view class="reply-list" v-if="item.showReplies && item.replies && item.replies.length">
            <view class="reply-item" v-for="reply in item.replies" :key="reply.id">
              <view class="reply-user">{{ reply.userName }}:</view>
              <view class="reply-content">{{ reply.content }}</view>
              <view class="reply-footer">
                <text class="reply-time">{{ reply.createTime }}</text>
                <view class="reply-like" @click="handleReplyLike(reply, item.id)">
                  <u-icon 
                    :name="reply.isLiked ? 'thumb-up-fill' : 'thumb-up'" 
                    size="16" 
                    :color="reply.isLiked ? '#00b578' : '#999'"
                  ></u-icon>
                  <text :class="{ 'liked': reply.isLiked }">{{ reply.likeCount || 0 }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="reply-input" v-if="item.showReplyInput">
            <u-input
              v-model="item.replyContent"
              type="text"
              placeholder="请输入回复内容"
              :border="true"
              :clearable="true"
            >
              <template #suffix>
                <u-button 
                  size="mini" 
                  type="primary" 
                  @click="submitReply(item)"
                  :loading="item.submitting"
                >
                  发送
                </u-button>
              </template>
            </u-input>
          </view>
        </view>
      </template>
    </view>

    <u-back-top :scroll-top="scrollTop"></u-back-top>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { storeToRefs } from 'pinia'
import { useReviewStore } from '../store/reviewStore'
import {onLoad} from '@dcloudio/uni-app'

const props = defineProps({
  fruitId: {
    type: [Number, String],
    required: true,
    default: '',
    validator: (value) => {
      const num = Number(value)
      return !isNaN(num) && num > 0
    }
  }
})

const reviewStore = useReviewStore()
const { stats, reviewList, loading } = storeToRefs(reviewStore)
const scrollTop = ref(0)
const refreshing = ref(false)

const filterTypes = computed(() => [
  { type: 0, label: '全部', count: stats.value.totalCount },
  { type: 1, label: '最新', count: stats.value.totalCount },
  { type: 2, label: '有图', count: stats.value.imageCount },
  { type: 3, label: '优质', count: stats.value.qualityCount }
])

const currentType = ref(0)

onLoad(async (option) => {
  const fruitDetailId = Number(option.fruitId)

  if (!fruitDetailId || isNaN(fruitDetailId)) {
    uni.showToast({
      title: '商品ID不能为空',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
    return
  }

  try {
    await reviewStore.loadReviewStats(fruitDetailId)
    await reviewStore.loadReviewList(fruitDetailId, currentType.value)
  } catch (error) {
    uni.showToast({
      title: '加载评价数据失败',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})

const handleFilterChange = async (type) => {
  const fruitDetailId = Number(props.fruitId)
  if (!fruitDetailId || isNaN(fruitDetailId)) {
    uni.showToast({
      title: '商品ID无效',
      icon: 'none'
    })
    return
  }

  try {
    currentType.value = type
    await reviewStore.loadReviewList(fruitDetailId, type)
  } catch (error) {
    uni.showToast({
      title: '切换评价类型失败',
      icon: 'none'
    })
  }
}

const handleLike = async (review) => {
  await reviewStore.toggleReviewLike(review.id)
}

const previewImage = (images, current) => {
  uni.previewImage({
    urls: images,
    current: images[current]
  })
}

const handleReplyLike = async (reply, reviewId) => {
  await reviewStore.toggleReplyLike(reply.id, reviewId)
}

const submitReply = async (review) => {
  if (!review.replyContent?.trim()) {
    uni.showToast({
      title: '请输入回复内容',
      icon: 'none'
    })
    return
  }

  review.submitting = true
  try {
    await reviewStore.submitReply({
      reviewId: review.id,
      content: review.replyContent
    })
    review.replyContent = ''
    review.showReplyInput = false
    uni.showToast({
      title: '回复成功',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: '回复失败',
      icon: 'error'
    })
  } finally {
    review.submitting = false
  }
}

const showReplyInput = async (review) => {
  if (!review.replies) {
    await reviewStore.loadReplyList(review.id)
  }
  review.showReplyInput = !review.showReplyInput
  review.showReplies = true
  review.replyContent = ''
}

const handlePageScroll = (e) => {
  scrollTop.value = e.scrollTop
}

const onRefresh = async () => {
  const fruitDetailId = Number(props.fruitId)
  if (!fruitDetailId || isNaN(fruitDetailId)) {
    uni.showToast({
      title: '商品ID无效',
      icon: 'none'
    })
    refreshing.value = false
    return
  }

  try {
    refreshing.value = true
    await reviewStore.loadReviewStats(fruitDetailId)
    await reviewStore.loadReviewList(fruitDetailId, currentType.value)
  } catch (error) {
    uni.showToast({
      title: '刷新评价数据失败',
      icon: 'none'
    })
  } finally {
    refreshing.value = false
  }
}

const loadData = async () => {
  try {
    const fruitDetailId = Number(props.fruitId)
    if (!fruitDetailId || isNaN(fruitDetailId)) {
      throw new Error('无效的商品ID')
    }
    await reviewStore.loadReviewStats(fruitDetailId)
    await reviewStore.loadReviewList(fruitDetailId, currentType.value)
  } catch (error) {
    uni.showToast({
      title: error.message || '加载评价数据失败',
      icon: 'none'
    })
  }
}

const handleDelete = async (review) => {
  try {
    const [res] = await uni.showModal({
      title: '确认删除',
      content: '确定要删除这条评价吗？',
      confirmColor: '#00b578'
    });
    
    if (res.confirm) {
      await reviewStore.deleteReview(review.id);
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
      await reviewStore.loadReviewStats(props.fruitId);
    }
  } catch (error) {
    uni.showToast({
      title: '删除失败',
      icon: 'error'
    });
  }
};

onMounted(() => {
  uni.onPageScroll(handlePageScroll)
  loadData()
})

onBeforeUnmount(() => {
  uni.offPageScroll(handlePageScroll)
  reviewStore.resetReviewData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/mixins.scss';
@import '@/styles/variables.scss';

.container {
  min-height: 100vh;
  background-color: $bg-color;
  padding-bottom: 30rpx;
}

.filter-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  padding: 20rpx 0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.filter-scroll {
  white-space: nowrap;
}

.filter-buttons {
  display: inline-flex;
  padding: 0 20rpx;
}

.filter-btn {
  display: inline-block;
  margin: 0 10rpx;
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: $text-color;
  background-color: $bg-color-light;
  transition: all 0.3s;
  
  &.active {
    background-color: rgba($primary-color, 0.1);
    color: $primary-color;
    font-weight: bold;
  }
}

.summary-card {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.summary-header {
  padding: 20rpx 30rpx;
  border-bottom: 1px solid $border-color-light;
}

.summary-title {
  font-size: 30rpx;
  font-weight: bold;
  color: $text-color;
  position: relative;
  padding-left: 20rpx;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6rpx;
    height: 30rpx;
    background-color: $primary-color;
    border-radius: 3rpx;
  }
}

.summary-content {
  display: flex;
  padding: 30rpx;
}

.summary-rating {
  display: flex;
  align-items: baseline;
  margin-right: 40rpx;
  
  .rating-score {
    font-size: 64rpx;
    font-weight: bold;
    color: #00b578;
  }
  
  .rating-max {
    font-size: 28rpx;
    color: $text-color-secondary;
    margin-left: 6rpx;
  }
}

.summary-stats {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  
  .stat-value {
    font-size: 28rpx;
    font-weight: bold;
    color: $text-color;
  }
  
  .stat-text {
    font-size: 24rpx;
    color: $text-color-secondary;
    margin-left: 10rpx;
  }

  u-rate {
    active-color: #00b578;
  }
}

.reviews-list {
  padding: 0 20rpx;
}

.review-card {
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid $border-color-light;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 16rpx;
  
  .user-name {
    font-size: 28rpx;
    color: $text-color;
    font-weight: bold;
    margin-bottom: 4rpx;
  }
  
  .user-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 10rpx;
    
    .user-time, .user-location {
      font-size: 22rpx;
      color: $text-color-secondary;
    }
  }
}

.rating-box {
  display: flex;
  align-items: center;
}

.review-content {
  padding: 20rpx;
}

.review-text {
  font-size: 28rpx;
  color: $text-color;
  line-height: 1.6;
}

.review-images {
  padding: 0 20rpx 20rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  
  .review-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 8rpx;
    object-fit: cover;
  }
}

.review-footer {
  display: flex;
  padding: 16rpx 20rpx;
  border-top: 1px solid $border-color-light;
  align-items: center;
}

.action-btn {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
  
  text {
    font-size: 24rpx;
    color: $text-color-secondary;
    margin-left: 6rpx;

    &.liked {
      color: #00b578;
    }
  }

  &:last-child {
    margin-left: auto;
  }
}

.load-more {
  text-align: center;
  margin: 30rpx 0;
}

.loading-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.reply-list {
  padding: 20rpx;
  background-color: $bg-color-light;
  margin: 0 20rpx 20rpx;
  border-radius: 8rpx;
}

.reply-item {
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.reply-user {
  font-size: 26rpx;
  color: #00b578;
  margin-bottom: 4rpx;
}

.reply-content {
  font-size: 26rpx;
  color: $text-color;
  line-height: 1.4;
}

.reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8rpx;
}

.reply-time {
  font-size: 22rpx;
  color: $text-color-secondary;
}

.reply-like {
  display: flex;
  align-items: center;
}

.reply-input {
  padding: 20rpx;
  background-color: $bg-color-light;
  margin: 0 20rpx 20rpx;
  border-radius: 8rpx;
}

:deep(.u-icon) {
  &.liked {
    color: #00b578;
  }
}
</style>
